package com.zegome.game.gomestory;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.ComponentName;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ResolveInfo;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.ColorFilter;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.PowerManager;
import android.os.PowerManager.WakeLock;
import android.util.Base64;
import android.view.KeyEvent;
import android.view.TextureView;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.TextureRegion;
import com.badlogic.gdx.scenes.scene2d.utils.TextureRegionDrawable;
import com.zegome.game.gomestory.main.A;
import com.zegome.game.gomestory.main.D;
import com.zegome.game.gomestory.main.helper.AndroidHelper;
import com.zegome.game.gomestory.main.helper.IOHelper;
import com.zegome.game.gomestory.main.helper.StageHelper;
import com.zegome.game.gomestory.main.helper.takephoto.CropOption;
import com.zegome.game.gomestory.main.helper.takephoto.CropOptionAdapter;

public class TakePhotoActivity extends Activity {	
	
	private Uri mImageCaptureUri;	
	private Bitmap photo;	
	private ImageView imageView;	
	private final int PICK_FROM_CAMERA = 1;
	private final int CROP_FROM_CAMERA = 2;
	private final int PICK_FROM_FILE = 3;
	
	boolean vi;
	private String title, okStr, cancelStr;
    private WakeLock wakeLock;
    
	@Override
    public void onCreate(Bundle savedInstanceState) {
    	
        super.onCreate(savedInstanceState);
        
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, 
                        WindowManager.LayoutParams.FLAG_FULLSCREEN);
        getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);		
  	  getWindow().addFlags( WindowManager.LayoutParams.FLAG_FULLSCREEN | WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD);    
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, 
                        WindowManager.LayoutParams.FLAG_FULLSCREEN);
        getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);
        
        setContentView(R.layout.takephoto_main_layout);
      	if(Locale.getDefault().getDisplayLanguage().equals("Tiếng Việt")){
      		vi = true;
      	}
      	else{
      		vi = false;
      	}
        title = vi?"Bạn chọn ảnh này làm avatar?":
 		   "You chose this photo to make avatar?";
        okStr = vi?"Đồng ý":"Ok";
        cancelStr = vi?"Tạo mới":"Create new";
        
        TextView titleLb = (TextView) findViewById(R.id.iv_text_title);
        titleLb.setText(title);
        
        imageView = (ImageView) findViewById(R.id.iv_photo);

		Button button 	= (Button) findViewById(R.id.iv_new);
		button.setText(cancelStr);
		
		button.setOnClickListener(new View.OnClickListener() {	
			@Override
			public void onClick(View v) {
				Intent intent = new Intent();
				
                intent.setType("image/*");
                intent.setAction(Intent.ACTION_GET_CONTENT);
                
                startActivityForResult(Intent.createChooser(intent, "Complete action using"), PICK_FROM_FILE);
			}
		});
		
		Button ok = (Button) findViewById(R.id.iv_ok);
		ok.setText(okStr);
		ok.setOnClickListener(new View.OnClickListener() {			
			@Override
			public void onClick(View v) {
				if(photo==null){
					finish();
					return;
				}
				// TODO Auto-generated method stub
	            /* Luu file anh vao sdcard */			            
	            String send;
	            try {
	     	       FileOutputStream out = new FileOutputStream("/sdcard/data/avatar/"+D.nameClone);
	     	       photo.compress(Bitmap.CompressFormat.PNG, 100, out);	     	       
	     	       out.flush();		     	       
	     	       out.close();
	           } catch (Exception e) {
	     	       e.printStackTrace();
	           }	           
	            
	            D.isChangeAvatar = true;
	        		            
					finish();					
					
			}
		});
		this.wakeLock = ((PowerManager)getSystemService("power")).newWakeLock(26, "take photo wakelock");
    }
    
	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		wakeLock.acquire();
		super.onResume();
	}
	
	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		wakeLock.release();
		super.onPause();
	}
	
    @Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
	    if (resultCode != RESULT_OK) return;
	   
	    switch (requestCode) {
		    case PICK_FROM_CAMERA:
		    	doCrop();		    	
		    	break;		    	
		    case PICK_FROM_FILE: 		    	
		    	mImageCaptureUri = data.getData();
		    	doCrop();	    
		    	break;	    		    
		    case CROP_FROM_CAMERA:	    	
		        Bundle extras = data.getExtras();
		        if (extras != null) {	        	
		            photo = extras.getParcelable("data");		            		           
		            imageView.setImageBitmap(photo);
		        }
	
		        mImageCaptureUri = Uri.fromFile(new File(Environment.getExternalStorageDirectory() +
						   "/tmp_avatar" + ".jpg"));
		        
		        File f = new File(mImageCaptureUri.getPath());            
		        
		        if (f.exists()) f.delete();        
		        //finish();
		        
		        break;

	    }
	}
    
    private void doCrop() {
		final ArrayList<CropOption> cropOptions = new ArrayList<CropOption>();
    	
    	Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setType("image/*");
        
        List<ResolveInfo> list = getPackageManager().queryIntentActivities( intent, 0 );
        
        int size = list.size();
        
        if (size == 0) {	        
        	Toast.makeText(this, "Can not find image crop app", Toast.LENGTH_SHORT).show();
        	
            return;
        } else {        	
        	
//        	mImageCaptureUri = Uri.fromFile(new File(Environment.getExternalStorageDirectory() +
//					   "/tmp_avatar" + ".jpg"));
        	
        	intent.setData(mImageCaptureUri);
        	
            intent.putExtra("outputX", 128);
            intent.putExtra("outputY", 128);
            
            intent.putExtra("aspectX", 1);
            intent.putExtra("aspectY", 1);
            
            intent.putExtra("scale", true);
            intent.putExtra("return-data", true);
            
        	if (size == 1) {
        		Intent i 		= new Intent(intent);
	        	ResolveInfo res	= list.get(0);
	        	
	        	i.setComponent( new ComponentName(res.activityInfo.packageName, res.activityInfo.name));
	        	
	        	startActivityForResult(i, CROP_FROM_CAMERA);
        	} else {
		        for (ResolveInfo res : list) {
		        	final CropOption co = new CropOption();
		        	
		        	co.title 	= getPackageManager().getApplicationLabel(res.activityInfo.applicationInfo);
		        	co.icon		= getPackageManager().getApplicationIcon(res.activityInfo.applicationInfo);
		        	co.appIntent= new Intent(intent);
		        	
		        	co.appIntent.setComponent( new ComponentName(res.activityInfo.packageName, res.activityInfo.name));
		        	
		            cropOptions.add(co);
		        }
	        
		        CropOptionAdapter adapter = new CropOptionAdapter(getApplicationContext(), cropOptions);
		        
		        AlertDialog.Builder builder = new AlertDialog.Builder(this);
		        builder.setTitle("Bạn chọn:");
		        builder.setAdapter( adapter, new DialogInterface.OnClickListener() {
		            public void onClick( DialogInterface dialog, int item ) {
		                startActivityForResult( cropOptions.get(item).appIntent, CROP_FROM_CAMERA);
		            }
		        });
	        
		        builder.setOnCancelListener( new DialogInterface.OnCancelListener() {
		            @Override
		            public void onCancel( DialogInterface dialog ) {
		               
//		            	mImageCaptureUri = Uri.fromFile(new File(Environment.getExternalStorageDirectory() +
//								   "/tmp_avatar" + ".jpg"));
		            	
		                if (mImageCaptureUri != null ) {
		                    getContentResolver().delete(mImageCaptureUri, null, null );
		                    mImageCaptureUri = null;
		                }
		            }
		        } );
		        
		        AlertDialog alert = builder.create();
		        
		        alert.show();
        	}
        }
	}
    
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		finish();
		return false;
	}
}